/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
 //searchable grid which allows to see everything the content filter has processed, failed or none
 //used to be feedgrid.js, need to change to json store 
TorrentsGrid = function(viewer, config) {
    this.viewer = viewer;
        
    this.columns = [{
        header: "Name",
        dataIndex: 'Name',
        sortable:true,
        width: 200,
        renderer: this.formatTitle
      },{
        header: "State",
        dataIndex: 'State',
        width: 100,
        hidden: false,
        sortable:true
      },{
        header: "Progress",
        dataIndex: 'progress',
        width: 120,
        hidden: false,
        sortable:true
      },{
        header: "Status",
        dataIndex: 'status',
        width: 100,
        hidden: false,
        sortable:true
      },{
        header: "DownloadSpeed",
        dataIndex: 'DownloadSpeed',
        width: 150,
        sortable:true
    }];
    
    Ext.apply(this, config);
    this.proxy =  new Ext.data.HttpProxy({
            method:'POST',
            url: '/gui/command.cgi'
            });
    this.reader = new Ext.data.JsonReader({
			    	root: 'torrents'
		    		
			},[
			    	{name: 'hash', mapping: 'hash'},
			    	{name: 'State', mapping: 'State'},
			    	{name: 'Name', mapping: 'Name'},
			    	{name: 'Size', mapping: 'Size'},
			    	{name: 'progress', mapping: 'progress'},
			    	{name: 'DataBytesDownloaded', mapping: 'DataBytesDownloaded'},
			    	{name: 'DataBytesUploaded', mapping: 'DataBytesUploaded'},
			    	{name: 'ratio', mapping: 'ratio'},
			    	{name: 'UploadSpeed', mapping: 'UploadSpeed'},
			    	{name: 'DownloadSpeed', mapping: 'DownloadSpeed'},
			    	{name: 'remSeconds', mapping: 'remSeconds'},
			    	{name: 'totalPeers', mapping: 'totalPeers'},
			    	{name: 'totalPeersCon', mapping: 'totalPeersCon'},
			    	{name: 'Seeds', mapping: 'Seeds'},
			    	{name: 'Seeds', mapping: 'SeedsCon'},
			    	{name: 'Availability', mapping: 'Availability'},
			    	{name: 'Complete', mapping: 'Complete'},
			    	 {name: 'Complete', mapping: 'remBytes'}  
			    
			]);
		
	this.store = new Ext.data.GroupingStore({
	        columns: this.columns,
            reader: this.reader,
            proxy: this.proxy,
            sortInfo:{field: 'State', direction: "DESC"}, //todo better default sort
            groupField:'State'
        });

    //this.store.setDefaultSort('pubDate', "DESC");
   this.tbar =   [
                {
                text: 'Start',
                tooltip: { title: 'Start', text: 'Starts/Resumes selected torrents' },
                iconCls: 'tabs',
                handler: this.startTorrents, //todo func
                scope: this
            },{
                text: 'Stop',
                tooltip: { title: 'Stop', text: 'Stops selected torrents' },
                iconCls: 'tabs',
                handler: this.stopTorrents, //todo func
                scope: this
            },{
                text: 'Remove',
                tooltip: { title: 'Start', text: 'Deletes selected torrents and optionally their associated data' },
                iconCls: 'tabs',
                handler: this.removeTorrents, //todo func
                scope: this
            },
            {
                text: 'Add by Url',
                tooltip: { title: 'Add by Url', text: 'Start a new torrent with the default settings, loading the torrent details from a remote URL' },
                iconCls: 'tabs',
                handler: this.addTorrentByUrl, //todo func
                scope: this
            },
        '-',


            {
                //todo correct type
                text: 'Details',
                tooltip: { title: 'Toggle Details', text: 'Toggles the details pane on or off' },
                iconCls: 'preview-bottom'
                //todohandler: this.movePreview.createDelegate(this, []),
                
                },
        '-',



                
                //Preferences button - spawns PreferencesWindow.js
{
                enableToggle: false,
                text: 'Preferences',
                iconCls: 'prefsicon', //TODO
                scope: this,
                handler: function() {
                    Ext.getCmp('preferences-win').form.getForm().setValues(prefs.defaultSources);
                    Ext.getCmp('preferences-win').show();
                }

            }
            ];
         

        
    

    TorrentsGrid.superclass.constructor.call(this, {
        region: 'center',
        id: 'torrents-panel',
        tbar: this.tbar,
        sm: new Ext.grid.RowSelectionModel({
            singleSelect:true
        }),

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:true,
            getRowClass : this.applyRowClass
        },
        view: new Ext.grid.GroupingView({
            forceFit:true,
            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
        })

    });

    this.on('rowcontextmenu', this.onContextClick, this);


 this.gsm = this.getSelectionModel();

//    this.gsm.on('rowselect', function(sm, index, record){
//        Application.getTemplate().overwrite(this.preview.body, record.data);
//        var items = this.preview.topToolbar.items;
//        items.get('tab').enable();
//        items.get('win').enable();
//    }, this, {buffer:250});

//    this.store.on('beforeload', this.preview.clear, this.preview);
//    this.store.on('load', this.gsm.selectFirstRow, this.gsm);

//    this.on('rowdblclick', this.openTab, this);

};


Ext.extend(TorrentsGrid, Ext.grid.GridPanel, {

    onContextClick : function(grid, index, e){
        if(!this.menu){ // create context menu on first right click
            this.menu = new Ext.menu.Menu({
                id:'torrentspanel-grid-ctx',
                items: [{
                    iconCls: 'new-win',
                    text: 'Start/Resume',
                    scope:this,
                    handler: function(){
                        window.open(this.ctxRecord.data.link);
                    }
                },'-',{
                    iconCls: 'refresh-icon',
                    text:'Stop',
                    scope:this,
                    handler: function(){
                        this.ctxRow = null;
                        this.store.reload();
                    }
                }]
            });
            this.menu.on('hide', this.onContextHide, this);
        }
        e.stopEvent();
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
        this.ctxRow = this.view.getRow(index);
        this.ctxRecord = this.store.getAt(index);
        Ext.fly(this.ctxRow).addClass('x-node-ctx');
        this.menu.showAt(e.getXY());
    },

    onContextHide : function(){
        if(this.ctxRow){
            Ext.fly(this.ctxRow).removeClass('x-node-ctx');
            this.ctxRow = null;
        }
    },

   

    togglePreview : function(show){
        this.view.showPreview = show;
        this.view.refresh();
    },

    // within this function "this" is actually the GridView
    applyRowClass: function(record, rowIndex, p, ds) {
        if (this.showPreview) {
            var xf = Ext.util.Format;
            p.body = '<p>' + xf.ellipsis(xf.stripTags(record.data.description), 200) + '</p>';
            return 'x-grid3-row-expanded';
        }
        return 'x-grid3-row-collapsed';
    },

    formatDate : function(date) {
        if (!date) {
            return '';
        }
        var now = new Date();
        var d = now.clearTime(true);
        var notime = date.clearTime(true).getTime();
        if (notime == d.getTime()) {
            return 'Today ' + date.dateFormat('g:i a');
        }
        d = d.add('d', -6);
        if (d.getTime() <= notime) {
            return date.dateFormat('D g:i a');
        }
        return date.dateFormat('n/j g:i a');
    },

    formatTitle: function(value, p, record) {
        return String.format(
                '<div class="topic"><b>{0}</b><span class="author">{1}</span></div>',
                value, record.data.author, record.id, record.data.forumid
                );
    }
});
